window.DtLbt = {};
DtLbt.labelCnt = 0;
DtLbt.title = "";
DtLbt.subTitle = "";
DtLbt.init = function(imgs, options) {
    DtLbt.imgs = imgs;
    if (options) {
        DtLbt.title = options.title;
        DtLbt.subTitle = options.subTitle;
    }
    console.log(document.currentScript.src)
    $.get('./js/r.html', function(rhtml) {
        $('.r-main').html(rhtml);

        DtLbt.mainImg = $('.r-img-main');
        DtLbt.mainImg.load(function(e) {
            DtLbt.mainImg.parent().css({
                'padding-top': (DtLbt.mainImg.parent().parent().height() - DtLbt.mainImg.height()) / 2 + "px"
            });
        });

        $('.r-row-1 .r-title span').html(DtLbt.title);
        $('.r-row-1 .r-subtitle span').html(DtLbt.subTitle);
        $('.r-lbt').html('');
        DtLbt.startIndex = 0;
        for (let index = 0; index < imgs.length && index < 3; index++) {
            const img = imgs[index];
            let tmpDom = '<li><img alt="' + img.alt + '" src="' + img.path + '" onclick="DtLbt.imgClick(this)"></li>';
            $('.r-lbt').append(tmpDom);
            DtLbt.startIndex++;
        }
        $("body").bind("click", function(e) {
            if ($(e.target).closest('.r-newDiv-textarea').length == 0) {
                $('.r-newDiv-textarea').css({
                    "display": "none"
                })
                $('.r-newDiv').css({
                    "display": "block"
                })
            }
        });
        $("#r-fontColor").colpick({
            onChange: function(hsb, hex, rgb, el, bySetColor) {
                $('.r-newDiv[current=true]').css({
                    'color': '#' + hex
                });
                $('#r-fontColor').css({
                    'background-color': '#' + hex
                });
            }
        });

        $('.r-btn-down').click(function(e) {
            DtLbt.next();
        });
        $('.r-btn-up').click(function(e) {
            DtLbt.pre();
        });
    });
}
DtLbt.cancelSel = function() {
    $('.r-newDiv').css('border-width', 0);
    $('.r-newDiv').attr('current', false);
}
DtLbt.save = function() {
    $('.r-newDiv').css('border-width', 0);
    html2canvas($('.r-Hb-main')[0], {
        taintTest: true, // 检测每张图片都已经加载完成
        logging: true, // 启用日志记录以进行调试 (发现加上对去白边有帮助)
        allowTaint: true, // 否允许跨源图像污染画布
        backgroundColor: null, // 解决生成的图片有白边
        useCORS: true, // 如果截图的内容里有图片,解决文件跨域问题
        timeout: 5000 // 加载延时
    }).then(canvas => {
        canvas.toBlob(blob => {
            var a = document.getElementById('r-img-export');
            a.href = URL.createObjectURL(blob);
            a.download = new Date().getTime() + '.png';
            a.click();
        }, 'image/png', 1);
    });
}
DtLbt.fontStyle = function(obj) {
    let b = $(obj).attr('italic');
    let val = "italic";
    if (b == 'italic') {
        val = "normal";
        $(obj).attr('italic', "");
    } else {
        val = "italic";
        $(obj).attr('italic', "italic");
    }
    $('.r-newDiv[current=true]').css({
        "font-style": val
    });
    $(obj).css({
        "font-style": val
    });
}
DtLbt.fontBold = function(obj) {
    let b = $(obj).attr('bold');
    let val = "bold";
    if (b == 'true') {
        val = "normal";
        $(obj).attr('bold', "false");
    } else {
        val = "bold";
        $(obj).attr('bold', "true");
    }
    $('.r-newDiv[current=true]').css({
        "font-weight": val
    });
    $(obj).css({
        "font-weight": val
    });
}
DtLbt.fontSize = function(upOrDown) {
    let value = $("#r-iSizeValue").val();
    value = parseInt(value);
    if (upOrDown) value += 1;
    else value -= 1;
    if (value < 6) value = 6;
    $("#r-iSizeValue").val(value);

    $('.r-newDiv[current=true]').css({
        "font-size": $("#r-iSizeValue").val() + "px"
    });
}
DtLbt.delLabel = function(obj) {
    $('.r-newDiv[current=true]').remove();
}
DtLbt.addLabel = function(obj) {
    let str = "新增文字，双击编辑，单击后按下拖动";
    if (obj != undefined) {
        str = $('.r-subtitle span').html();
    }
    let divNew = "<div class='r-newDiv r-newDiv-base' tagIndex='" + DtLbt.labelCnt + "' onclick='DtLbt.onClickLabel(this)' ondblclick='DtLbt.ondblclick(this)'>" + str + "</div>";
    let textAreaNew = "<textarea style='display:none;' class='r-newDiv-textarea r-newDiv-base' tagIndex='" + DtLbt.labelCnt + "'  ondblclick='DtLbt.ondblclick(this)'>" + str + "</textarea>";
    $('.r-Hb-main').append(divNew);
    $('.r-Hb-main').append(textAreaNew);

    $('.r-newDiv-textarea[tagIndex=' + DtLbt.labelCnt + ']').bind('input propertychange', function(e) {
        let tagIndex = $(e.target).attr('tagIndex');
        $('.r-newDiv[tagIndex=' + tagIndex + ']').html($(e.target).val());
    });

    $('.r-newDiv-textarea[tagIndex=' + DtLbt.labelCnt + ']').bind('mouseup mousemove', function(e) {
        let tagIndex = $(e.target).attr('tagIndex');
        $('.r-newDiv[tagIndex=' + tagIndex + ']').css({
            height: $(e.target).css('height'),
            width: $(e.target).css('width')
        });
    });
    //make editable

    ///
    DtLbt.dragDom($('.r-newDiv[tagIndex=' + DtLbt.labelCnt + ']'));

    DtLbt.labelCnt++;
}
DtLbt.onClickLabel = function(obj) {
    $('.r-newDiv').css('border-width', 0);
    $('.r-newDiv').attr('current', false);
    $(obj).css('border', '1px solid red');
    $(obj).attr('current', true);
}
DtLbt.ondblclick = function(obj) {
    $(obj).css('display', 'none');
    let tagIndex = $(obj).attr('tagIndex');
    theTextarea = $('.r-newDiv-textarea[tagIndex=' + tagIndex + ']');
    theTextarea.css({
        "display": "",
        left: $(obj).css('left'),
        top: $(obj).css('top'),
        height: $(obj).css('height'),
        width: $(obj).css('width')
    });
}
DtLbt.imgClick = function(obj) {
    DtLbt.mainImg.attr('src', $(obj).attr('src'));
}
DtLbt.pre = function() {
    if (DtLbt.imgs.length < 2) return;
    if (DtLbt.startIndex >= DtLbt.imgs.length) DtLbt.startIndex = 0;
    let img = DtLbt.imgs[DtLbt.startIndex];
    $('.r-lbt').find('li').eq(0).remove();
    let tmpDom = '<li><img alt="' + img.alt + '" src="' + img.path + '" onclick="DtLbt.imgClick(this)"></li>';
    let lis = $('.r-lbt').find('li');
    lis.eq(lis.length - 1).after(tmpDom);
    DtLbt.startIndex = DtLbt.startIndex + 1;
}
DtLbt.next = function() {
    if (DtLbt.imgs.length < 2) return;
    if (DtLbt.startIndex < 0) DtLbt.startIndex = DtLbt.imgs.length - 1;
    let img = DtLbt.imgs[DtLbt.startIndex];
    let lis = $('.r-lbt').find('li');
    lis.eq(lis.length - 1).remove();
    let tmpDom = '<li><img alt="' + img.alt + '" src="' + img.path + '" onclick="DtLbt.imgClick(this)"></li>';
    $('.r-lbt').find('li').eq(0).before(tmpDom);
    DtLbt.startIndex = DtLbt.startIndex - 1;
}

function changeM() {
    var inputJ = $("#r-changeMore"),
        input = inputJ[0],
        Con = $("#r-ImgCon");

    inputJ.change(function(e) {
        var file = e.target.files[0], //拿到原始对象
            thisType = file.type, //获取到表面的名称，可判断文件类型
            thisSize = file.size, //文件的大小
            thisSrc = URL.createObjectURL(file), //当前对象的地址
            img = $('<img>').attr('src', thisSrc); //创建img对象
        DtLbt.mainImg.attr('src', thisSrc);
        //文件加载成功以后，渲染到页面
        img.load(function() {
            Con.append(img);
            URL.revokeObjectURL(thisSrc); //释放内存
        });
    });
} //
changeM();

DtLbt.dragDom = function(jdom) {
    return function(theJdom) {
        let theDom = theJdom;
        theJdom.mousedown(function(e) {
            let pt = $('.r-Hb-main');
            // e.pageX
            var positionDiv = $(this).offset();
            var distenceX = e.pageX - positionDiv.left;
            var distenceY = e.pageY - positionDiv.top;
            //alert(distenceX)
            // alert(positionDiv.left);
            pt.mousemove(function(e) {
                if (!(theDom.attr('current') == 'true')) return;
                var x = e.pageX - distenceX - pt.offset().left;
                var y = e.pageY - distenceY - pt.offset().top;

                if (x < 0) {
                    x = 0;
                } else if (x > pt.width() - theDom.outerWidth(true)) {
                    x = pt.width() - theDom.outerWidth(true);
                }

                if (y < 0) {
                    y = 0;
                } else if (y > pt.height() - theDom.outerHeight(true)) {
                    y = pt.height() - theDom.outerHeight(true);
                }

                theDom.css({
                    'left': x + 'px',
                    'top': y + 'px'
                });
            });

            pt.mouseup(function() {
                pt.off('mousemove');
            });
        });
    }(jdom);
}